package cn.learn.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * 创建elasticsearc的对象；
 * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-getting-started-initialization.html
 *
 * @author huangyezhan
 * @version 1.0
 * @date 2020年06月21日21:41
 */
@Configuration
public class ElasticsearchConfig {

    private final String[] ips;

    public ElasticsearchConfig(ElasticsearchProperties elasticsearchProperties) {
        this.ips = elasticsearchProperties.getIps();
    }

    @Bean
    public RestHighLevelClient restHighLevelClient() throws IOException {
        //动态设置es的访问链接
        HttpHost[] https = new HttpHost[ips.length];
        for (int i = 0; i < https.length; i++) {
            String[] split = ips[i].split(":");
            https[i] = new HttpHost(split[0], Integer.parseInt(split[1]), "http");
        }

        return new RestHighLevelClient(RestClient.builder(https));
    }

}
